package com.xwqiang.utils;

import com.alibaba.fastjson2.JSON;

import java.util.*;

/*****
 * @Author:
 * @Description:支付安全处理
 *                解密、验签
 ****/
public class Signature {

    //秘钥
    private String skey;

    //验签加盐值
    private String salt;

    public Signature(String skey, String salt) {
        this.skey = skey;
        this.salt = salt;
    }

    /***
     * 密文解密，并转成Map,并对Map数据进行验签
     * @param ciphertext
     * @return
     */
    public Map<String,String> security(String ciphertext) throws Exception {
        //1.解密
        String decrypt =new String( AESUtil.encryptAndDecrypt(Base64Util.decodeURL(ciphertext), skey,2) , "UTF-8");
        //2.明文转Map并根据Key降序
        Map<String,String> decryptTreeMap = JSON.parseObject(decrypt,TreeMap.class);
        //3.验签
        String signature = decryptTreeMap.remove("signature");
        String localSignature = MD5.md5(JSON.toJSONString(decryptTreeMap),salt);
        //true 验签成功，false  验签失败
        return signature.equals(localSignature)? decryptTreeMap : null;
    }


    /***
     * Map加密，携带验签
     */
    public String security(Map<String,String> dataMap) throws Exception {
        //1.将dataMap转成TreeMap
        dataMap = JSON.parseObject(JSON.toJSONString(dataMap),TreeMap.class);
        //2.将TreeMap转成JSON
        String treeJson = JSON.toJSONString(dataMap);
        //3.执行MD5摘要加密
        String signature = MD5.md5(treeJson,salt);
        //4.摘要加密内容添加到dataMap中
        dataMap.put("signature",signature);
        //5.AES加密dataMap
        return Base64Util.encodeURL(AESUtil.encryptAndDecrypt(JSON.toJSONString(dataMap).getBytes("UTF-8"),skey,1));
    }

}
